<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <video id="video" playsinline></video>
    <button onclick="unmuted()">unmuted</button>
</body>
<script src="https://unpkg.com/vconsole@latest/dist/vconsole.min.js"></script>
<script>
    var vConsole = new window.VConsole();
    const ws = new WebSocket('wss://192.168.6.61:8080/message_websocket/b')
    // const RTCPeerConnection = window.RTCPeerConnection || window.mozRTCPeerConnection || window.webkitRTCPeerConnection
    const config = {
        sdpSemantics: "unified-plan",
        iceTransportPolicy: "all",
        iceServers: [
            {
                urls: 'stun:47.114.110.197:23478',
            }
        ]
    }
    const pc = new RTCPeerConnection(config)
    ws.addEventListener('message', async (e) => {
        const msg = JSON.parse(e.data)

        if (msg.action === 'icecandidate') {
            if (msg.data) {
                pc.addIceCandidate(JSON.parse(msg.data))
            }
        }

        if (msg.action === 'description') {
            await pc.setRemoteDescription(JSON.parse(msg.data))
            const answer = await pc.createAnswer()
            await pc.setLocalDescription(answer)
            const command = {
                action: 'description',
                to: 'a',
                data: answer
            }
            ws.send(JSON.stringify(command))
        }
    });

    pc.addEventListener('icecandidate', (e) => {
        console.log('on icecandidate')
        const msg = {
            action: 'icecandidate',
            to: 'a',
            data: e.candidate
        }
        ws.send(JSON.stringify(msg))
    })

    pc.addEventListener('track', (e) => {
        console.log('on track')
        document.querySelector('#video').srcObject = e.streams[0]
    })

    function unmuted() {
        document.querySelector('#video').muted = false
        document.querySelector('#video').play()
    }
</script>

</html>